﻿using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	public class SortingBinder : IModelBinder
	{
		private static string _propertyNameKey;
		private static string _sortDirectionKey;

		public static string PropertyNameKey
		{
			get
			{
				if (string.IsNullOrEmpty(_propertyNameKey))
				{
					_propertyNameKey = "sort";
				}

				return _propertyNameKey;
			}
			set { _propertyNameKey = value; }
		}

		public static string SortDirectionKey
		{
			get
			{
				if (string.IsNullOrEmpty(_sortDirectionKey))
				{
					_sortDirectionKey = "direction";
				}

				return _sortDirectionKey;
			}
			set { _sortDirectionKey = value; }
		}

		public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			Guard.NotNull(bindingContext, "bindingContext");

			var propertyName = bindingContext.GetValueOrDefault(PropertyNameKey, "Id");
			var sortDirection = bindingContext.GetValueOrDefault(SortDirectionKey, SortDirection.Ascending);

			return new Sorting(propertyName, sortDirection);
		}
	}
}